package com.itheima.demo04JDBC事务_重点;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo04 {
	public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 1.注册驱动(自动注册)
            // 2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day18", "root", "root");
            // 3.开启事务, false表示开启事务
            conn.setAutoCommit(false);
            // 4.获取到Statement
            stmt = conn.createStatement();
            // 5.Statement执行SQL
            // 张三-500
            stmt.executeUpdate("UPDATE account SET balance=balance-500 WHERE id=1;");
            int a = 10 / 0; // ArimethicException 数学计算异常
            // 李四+500
            stmt.executeUpdate("UPDATE account SET balance=balance+500 WHERE id=2;");
            // 6.成功提交事务
            conn.commit();
            System.out.println("成功提交事务");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败回滚事务");
            // 6.失败回滚事务
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
